package com.swe727.spring2011.constraint1.server;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.HashSet;

import com.swe727.spring2011.constraint1.client.ClientMedevacRemote;
import com.swe727.spring2011.constraint1.coordinate.Coordinate;
import com.swe727.spring2011.constraint1.message.Message;
import com.swe727.spring2011.constraint1.node.Node;
import com.swe727.spring2011.constraint1.node.NodeDataStore;

public class ServerMedevacHandler implements ServerMedevacRemote {

	@Override
	public void requestMedevac(Coordinate coordinate) throws RemoteException {
		// get all the nodes
		HashSet<Message<Node>> nodes = NodeDataStore.getStore().getAll(null);
		System.out.println("Medevac request received!");
		
		// we should make this multi-thread with Future or just using Threads
		for (Message<Node> msg : nodes) {
			Node node = msg.getData();
			String id = node.getNodeId();
			String ip = node.getIPAddress();
			int port = node.getPort();
			
			Registry registry;
			try {
				registry = LocateRegistry.getRegistry(ip, port);
				ClientMedevacRemote handler = (ClientMedevacRemote) registry.lookup(id);
				handler.receiveMedevac(coordinate);
			} catch (RemoteException e) {
				e.printStackTrace();
			} catch (NotBoundException e) {
				e.printStackTrace();
			}			
		}
	}
}
